﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class Game : MonoBehaviour {

	public PointCloudGestureRenderer GestureRendererPrefab;
	List<PointCloudGestureRenderer> gestureRenderers;
	public GameObject theComboText;
	void Start () {
		RenderNextGesture();
	
	}
	void onCompleteDrawing( PointCloudGesture gesture ) 
	{ 
		string scorePercentText = ( gesture.MatchScore * 100 ).ToString( "N2" );
		
		string statusText = "Matched " + gesture.RecognizedTemplate.name + " (score: " + scorePercentText + "% distance:" + gesture.MatchDistance.ToString( "N2" ) + ")";
		if (currentTemplateName ==  gesture.RecognizedTemplate.name) {
			RenderNextGesture();
			currentCombo++;
			theComboText.GetComponent<Text>().text="Combo : "+ currentCombo;
		}
	}

	// Update is called once per frame
	void Update () {
	
	}

	#region Combo
	int currentCombo = 0;
	private PointCloudGestureRenderer gestureRenderer;
	Transform gestureRoot;
	private string currentTemplateName;
	void RenderNextGesture(){
		gestureRenderers = new List<PointCloudGestureRenderer>();
		if (gestureRoot) {
			Destroy(gestureRoot.gameObject);
		}
		gestureRoot = new GameObject( "Gesture Templates" ).transform;
		gestureRoot.parent = this.transform;
		gestureRoot.localScale = 10.0f * Vector3.one;
		PointCloudRegognizer recognizer = GetComponent<PointCloudRegognizer>();
		Vector3 pos = Vector3.zero;
		int gesturesOnRow = 0;
		int rows = 0;
		float rowWidth = 0;


		int theRandomTemp = (int)Random.Range (0.0f, (float)recognizer.Templates.Count);
		Debug.Log(  theRandomTemp);
		PointCloudGestureTemplate template = recognizer.Templates[theRandomTemp];
		currentTemplateName = template.name;
		gestureRenderer = Instantiate( GestureRendererPrefab, gestureRoot.position, gestureRoot.rotation ) as PointCloudGestureRenderer;
		gestureRenderer.GestureTemplate = template;
		gestureRenderer.name = template.name;
		gestureRenderer.transform.parent = gestureRoot;
		gestureRenderer.transform.localPosition = new Vector3(0,0,0);
		gestureRenderer.transform.localScale = Vector3.one;
		gestureRenderers.Add( gestureRenderer );
		iTween.ScaleTo(gestureRoot.gameObject,iTween.Hash("x",1,"y",1,"z",1,"time",3.0f,"easetype","linear","oncomplete","onFinishScale","oncompletetarget",gameObject));
		//iTween.FadeTo(gestureRoot.gameObject,iTween.Hash("alpha",0,"time",5.0f,"easetype","linear"));
	}

	void onFinishScale(){
		RenderNextGesture ();
		currentCombo=0;
		theComboText.GetComponent<Text>().text="Combo : "+ currentCombo;
	}
	#endregion

	#region Misc

	PointCloudGestureRenderer FindGestureRenderer( PointCloudGestureTemplate template )
	{
		return gestureRenderers.Find( gr => gr.GestureTemplate == template );
	}

	#endregion 
}
